package com.le.tester.webpage.redis.service.impl;

import com.le.tester.common.enums.RedisKey;
import com.le.tester.utils.RedisUtil;
import com.le.tester.webpage.redis.service.RedisRankingService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.DefaultTypedTuple;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * 描述：redis实时排序逻辑实现
 */
@Service
public class RedisRankingServiceImpl implements RedisRankingService {

    private static final Logger LOG = LoggerFactory.getLogger(RedisRankingServiceImpl.class);

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 获取前十的排行
     *
     * @return
     */
//    static {
//        LOG.info("静态加载，批量插入数据");
//        batchAdd();
//    }
    @Override
    public Map<String, Object> getTopTen() {
        this.batchAdd();
        Map<String, Object> resultMap = new HashMap<>();
        Set<ZSetOperations.TypedTuple<Object>> ranges = redisUtil.zgetSetbyScore(RedisKey.SCORE_RANK.getCode(), 0, 10);
        LOG.info("获取到的排行列表：{}", ranges);
        Set<ZSetOperations.TypedTuple<Object>> rangeWithScores = redisUtil.zgetSet(RedisKey.SCORE_RANK.getCode(), 0, 10);
        LOG.info("获取到的排行和分数列表，{}", rangeWithScores);
        resultMap.put("ranges", ranges);
        resultMap.put("rangesWithScores", rangeWithScores);
        return resultMap;
    }

    /**
     * 批量添加zSet
     */
    private void batchAdd() {
        Set<ZSetOperations.TypedTuple<Object>> tuples = new HashSet<>();
//        String start = LocalDateTime.now().format(DateTimeFormatter.ofPattern(Const.STANDARD_FORMAT));
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < 1000; i++) {
            //设置值和权重（排序）
            DefaultTypedTuple<Object> tuple = new DefaultTypedTuple<Object>("张三" + i, 1D + i);
            tuples.add(tuple);
        }
        System.out.println("循环时间：" + (System.currentTimeMillis() - startTime));
        //批量的新增
        long num = redisUtil.zsetSet(RedisKey.SCORE_RANK.getCode(), tuples);
        System.out.println("批量新增的时间：" + (System.currentTimeMillis() - startTime));
        System.out.println("受影响的行数：" + num);
    }
}
